<script setup>
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores'
import { userUpdateAvatarService } from '@/api/user.js'
// 基于store的数据，初始化imgUrl的初始值
const userStore = useUserStore()
const imgUrl = ref(userStore.user.user_pic)
// 点击选择图片 预览图片
const uploadRef = ref()
const onSelectFile = (uploadFile) => {
  const reader = new FileReader()
  reader.readAsDataURL(uploadFile.raw)
  reader.onload = () => {
    imgUrl.value = reader.result
    console.log(imgUrl.value) // base64位图片格式
  }
  // imgUrl.value = URL.createObjectURL(uploadFile.raw)
}
// 点击上传头像
const onUpdateAvatar = async () => {
  // 发送请求更新头像
  await userUpdateAvatarService(imgUrl.value)
  // userStore 重新渲染
  await userStore.getUser()
  // 成功提示
  ElMessage.success('更新成功')
}
</script>

<template>
  <PageContainer title="更换头像">
    <el-upload class="avatar-uploader" ref="uploadRef" :show-file-list="false" :auto-upload="false" :on-change="onSelectFile">
      <img v-if="imgUrl" :src="imgUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <el-button @click="uploadRef.$el.querySelector('input').click()" type="primary"><el-icon><Plus /></el-icon>选择图片</el-button>
    <el-button @click="onUpdateAvatar" type="success"><el-icon><Upload /></el-icon>上传头像</el-button>
  </PageContainer>
</template>

<style lang="scss" scoped>
.avatar-uploader{
  margin-bottom: 20px;
  :deep() {
    .avatar{
      width: 188px;
      height: 188px;
      display: block;
    }
    .el-upload{
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover{
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon{
      font-size: 28px;
      color: #8c939d;
      width: 188px;
      height: 188px;
      text-align: center;
    }
  }
}
</style>
